/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mvc.controlador;


import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import mvc.helper.DebugBase;
import mvc.helper.FeedbackBase;

/**
 * La Clase Controlador es el que redirige a nivel global las operaciones dentro del
 * Sistema
 * @author PezEspada
 */
public class Controlador extends HttpServlet {
       HttpSession session;
       HttpServletRequest request;
       ///> feedback_mvc Retroalimentacion para el Cliente
       FeedbackBase feedback_mvc = new FeedbackBase();
       ///> debug_mvc Retroalimentacion para el Desarrollador
       DebugBase debug_mvc = new DebugBase();



    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param req servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest req, HttpServletResponse response)
    throws ServletException, IOException {
        request = req;
        session = request.getSession();
        debug_mvc.Inicializa_vars();
        //Variable que almacena el nombre del controlador de 2 Capa
        String go_Controlador;
       ///> INICIALIZACION GENERAL DEL SISTEMA - 3 NIVELES [ SYSTEM - USUARIO - ACCION ]
       mvc_init();
       ///> ENRUTANDO LA PETICION
       ///> parametro de entrada <mid>
       String moduloid = this.getValid_Request_Param_String( "mid" );
       //SE ESCOJE EL MODULO a redireccionar segun <mid>
       if( moduloid.equalsIgnoreCase("SYS1") || moduloid.equalsIgnoreCase("sys1") ){
            request.setAttribute("modulo_id", "SYS1" );
            go_Controlador = "SGC1Controlador";
       }else if( moduloid.equalsIgnoreCase("AY") || moduloid.equalsIgnoreCase("ay") ){
            request.setAttribute("modulo_id", "AY" );
            go_Controlador = "AYControlador";
       }else if( moduloid.equalsIgnoreCase("error") || moduloid.equalsIgnoreCase("ERROR") ){
            request.setAttribute("modulo_id", "ERR" );
            go_Controlador = "ErrorControlador";
       }else {
            request.setAttribute("modulo_id", "DF" );
            go_Controlador = "DFControlador";
       }
          ///>Redireccionando al nivel del servidor
          ///>///////////////////////////////////////////////////////////////////
          ///>///////////////////////////////////////////////////////////////////
          request.setAttribute("debug_mvc", debug_mvc );
          request.setAttribute("feedback_mvc", feedback_mvc );
          RequestDispatcher rd = request.getRequestDispatcher( go_Controlador);
          rd.forward(request, response);
    } 



    protected Boolean mvc_init(){
      ///> APPLICACION <applicationScope> -> Inicializacion
      if( session.getAttribute("APPLICACION_INICIADA") == null  ){
          session.setAttribute("APPLICACION_INICIADA", true);
          //CONSTANTES
          this.getServletContext().setAttribute("_PARAM_SIN_VALOR", "index");
      }
      ///> USUARIO <sessionScope> -> Inicializacion
      if( session.getAttribute("SESSION_INICIADA")  == null  ){
          session.setAttribute("SESSION_INICIADA" , true);
          
          //Define el userAgent para MOzilla, iPhone,  Android, BlackBerry
          if( request.getHeader("user-agent") !=null ){
            setUserAgentBrowser( request.getHeader("user-agent") ); }
          else{
             session.setAttribute("user_agent","WEB-INF/Layout/Browser.jsp" );
             session.setAttribute("user_agent_type","COMPUTER" );
          }
      }
      ///> ACCION <requestScope> -> Inicializacion

      return true;
    }




 
    // <editor-fold defaultstate="collapsed" desc="Funciones heredadas del Servlet.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>


     // <editor-fold defaultstate="collapsed" desc="Funciones auxiliares">

    /***
     * @param userAgent : dljslñf
     * Seteamos el User Agent
     * Tiene alcance de Request. deberia pasar a alcance de Sesion
     */
    protected void setUserAgentBrowser( String userAgent ){
       //CAPTURAMOS EL USER_AGENT
       if( userAgent.toUpperCase().indexOf("IPHONE") > 0 ){
          session.setAttribute("user_agent_type","MOBILE" );
          session.setAttribute("user_agent","WEB-INF/Layout/Iphone.jsp" );
       }else if( userAgent.indexOf("Android") > 0 ){
         session.setAttribute("user_agent_type","MOBILE" );
          session.setAttribute("user_agent","WEB-INF/Layout/Android.jsp" );
       }else if( userAgent.indexOf("BlackBerry") > 0 ){
         session.setAttribute("user_agent_type","MOBILE" );
         session.setAttribute("user_agent","WEB-INF/Layout/Blackberry.jsp" );
       }else{
         session.setAttribute("user_agent","WEB-INF/Layout/Browser.jsp" );
         session.setAttribute("user_agent_type","COMPUTER" );
       }
    }

    protected String getValid_Request_Param_String( String param_name ){
      String param_final ="index";
      if( request.getParameter(param_name) != null ){
        if( request.getParameter(param_name).trim() != null ){
          param_final = request.getParameter(param_name).trim();
        }
      }
    return param_final;
   }


//</editor-fold>
    
}
